<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { Search, ArrowLeft, Check } from '@element-plus/icons-vue'; // 引入Check图标
import {
  ElMessage,
  ElButton,
  ElInput,
  ElRadioGroup,
  ElRadioButton,
  ElSelect,
  ElOption,
  ElPagination,
  ElEmpty,
  ElIcon,
} from 'element-plus';
import ResourceItem from '@/resource/ResourceItem.vue';
import resourceService from '@/services/resourceService.js';
import { userManager } from '@/utils/user';

// 响应式数据
const searchParams = reactive({
  keyword: '',
  major: '全部',
  type: '全部',
  difficulty: '全部',
  sort: '综合排序',
  page: 1,
  pageSize: 20,
});

const resourceList = ref([]);
const totalResources = ref(0);
const loading = ref(false);
const ownedResourceIds = ref(new Set());

const categoryMap = {
  'PDF': 0, '视频': 1, '图片': 2, 'PPT': 3, 'Zip': 4, 'Excel': 5,'其他': 6,
};
const difficultyMap = {
  '简单': 0, '中等': 1, '困难': 2, '高阶': 3,
};

// 筛选选项的静态数据
const filterOptions = {
  major: ['全部', '哲学','经济学','金融学','法学','马克思主义理论','教育学','体育',
    '文学','历史学','数学','物理学','化学','天文学','地理学','力学类','机械',
    '材料','能源类','电气','自动化','计算机','电子信息','矿业','土木水利',
    '农学','医学','药学','管理学','艺术类'],
  type: ['全部', 'PDF', '视频', '图片', 'PPT', 'Zip', 'Excel', '其他'],
  difficulty: ['全部', '简单', '中等', '困难', '高阶'],
  sort: ['综合排序', '学分最高', '按难度'],
};

// 处理购买成功的事件
function handlePurchaseSuccess(purchasedResource) {
  if (purchasedResource && purchasedResource.id) {
    ownedResourceIds.value.add(purchasedResource.id);
  }
}

// 调用API获取资源
async function fetchResources() {
  loading.value = true;
  try {
    const paramsToSend = {
      page: searchParams.page,
      size: searchParams.pageSize,
      q: searchParams.keyword,
    };
    if (searchParams.major !== '全部') paramsToSend.major = searchParams.major;
    if (searchParams.type !== '全部') paramsToSend.category = categoryMap[searchParams.type];
    if (searchParams.difficulty !== '全部') paramsToSend.difficulty = difficultyMap[searchParams.difficulty];

    if (searchParams.sort && searchParams.sort !== '综合排序') {
      let sortParam = '';
      switch (searchParams.sort) {
        case '学分最高':sortParam = 'credit,desc';break;
        case '按难度':sortParam = 'difficulty,asc';break;}
      if (sortParam) {paramsToSend.sort = sortParam;}
    }

    const response = await resourceService.getResources(paramsToSend);
    if (response && response.success) {
      resourceList.value = response.data.records || [];
      totalResources.value = response.data.total || 0;

      const currentUserId = userManager.getUserId();
      if (currentUserId && resourceList.value.length > 0) {
        const resourceIdsOnPage = resourceList.value.map(r => r.id);
        const purchasedIds = await resourceService.checkOwnership(currentUserId, resourceIdsOnPage);

        resourceList.value.forEach(resource => {
          if (resource.publisherId === currentUserId) {
            purchasedIds.add(resource.id);
          }
        });

        ownedResourceIds.value = purchasedIds;
      } else {
        ownedResourceIds.value.clear();
      }

    } else {
      ElMessage.error(response.message || '获取资源列表失败');
      resourceList.value = [];
      totalResources.value = 0;
    }
  } catch (error) {
    console.error("请求资源列表失败:", error);
    ElMessage.error('网络错误，无法连接到服务器');
  } finally {
    loading.value = false;
  }
}

// 统一的搜索处理函数
function handleSearch() {
  searchParams.page = 1;
  fetchResources();
}

// 事件处理：页码改变
function handlePageChange(newPage) {
  searchParams.page = newPage;
  fetchResources();
}

// 监听筛选参数的变化
watch(
    () => [searchParams.major, searchParams.type, searchParams.difficulty, searchParams.sort],
    () => {
      handleSearch();
    },
    { deep: true }
);

// 组件挂载后，立即获取一次数据
onMounted(fetchResources);

function goBack() {
  window.history.back();
}
</script>

<template>
  <div class="search-resource-page">
    <div class="top-search-bar">
      <div class="search-container">
        <el-button class="back-btn" :icon="ArrowLeft" text circle @click="goBack" />
        <el-input
            v-model="searchParams.keyword"
            placeholder="搜索您感兴趣的资源、知识或技能"
            size="large"
            clearable
            @keyup.enter="handleSearch"
            @clear="handleSearch"
            class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <div class="main-layout-container">
      <div class="left-sidebar">
        <h3 class="panel-title">资源筛选</h3>
        <div class="filter-group">
          <span class="filter-label">专业</span>
          <el-select v-model="searchParams.major" filterable placeholder="请选择或搜索专业" style="width: 100%;">
            <el-option v-for="item in filterOptions.major" :key="item" :label="item" :value="item"/>
          </el-select>
        </div>
        <div class="filter-group">
          <span class="filter-label">类型</span>
          <el-radio-group v-model="searchParams.type" class="chip-radio-group">
            <el-radio-button v-for="item in filterOptions.type" :key="item" :label="item">
              <el-icon v-if="searchParams.type === item && item !== '全部'"><Check /></el-icon>
              {{ item }}
            </el-radio-button>
          </el-radio-group>
        </div>
        <div class="filter-group">
          <span class="filter-label">难度</span>
          <el-radio-group v-model="searchParams.difficulty" class="chip-radio-group">
            <el-radio-button v-for="item in filterOptions.difficulty" :key="item" :label="item">
              <el-icon v-if="searchParams.difficulty === item && item !== '全部'"><Check /></el-icon>
              {{ item }}
            </el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <div class="right-content">
        <div class="sort-section">
          <el-radio-group v-model="searchParams.sort" size="small" class="chip-radio-group sort-chips">
            <el-radio-button v-for="item in filterOptions.sort" :key="item" :label="item" />
          </el-radio-group>
          <div class="total-text">共 {{ totalResources }} 个相关资源</div>
        </div>

        <div v-loading="loading" class="resource-grid-container">
          <div v-if="!loading && resourceList.length > 0" class="resource-grid">
            <ResourceItem
                v-for="resource in resourceList"
                :key="resource.id"
                :resource="resource"
                :is-purchased="ownedResourceIds.has(resource.id)"
                @redeem-success="handlePurchaseSuccess"
                :navigation-enabled="false"
            />
          </div>
          <el-empty v-if="!loading && resourceList.length === 0" description="没有找到相关资源，换个关键词试试？" />
        </div>

        <div class="pagination-container" v-if="!loading && totalResources > searchParams.pageSize">
          <el-pagination
              background
              layout="prev, pager, next"
              :total="totalResources"
              :page-size="searchParams.pageSize"
              :current-page="searchParams.page"
              @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>

.search-resource-page {
  background-color: #f7f8fa;
  min-height: 100vh;
}

.top-search-bar {
  background: white;
  padding: 12px 0;
  position: sticky;
  top: 0;
  z-index: 100;
  border-bottom: 1px solid #e4e7ed;
}
.search-container {
  display: flex;
  align-items: center;
  gap: 12px;
  max-width: 1280px;
  margin: 0 auto;
  padding: 0 24px;
}
.search-input :deep(.el-input__wrapper) {
  border-radius: 20px !important;
  box-shadow: none !important;
  background-color: #f1f3f4;
}
.search-input :deep(.el-input__wrapper.is-focus) {
  background-color: #fff;
  box-shadow: 0 0 0 1px var(--el-color-primary) inset !important;
}


.main-layout-container {
  display: flex;
  gap: 32px;
  max-width: 1280px;
  margin: 24px auto;
  padding: 0 24px;
  align-items: flex-start;
}
.left-sidebar {
  width: 240px;
  flex-shrink: 0;
  position: sticky;
  top: 85px;
}
.right-content {
  flex: 1;
  min-width: 0;
}


.panel-title {
  font-size: 18px;
  font-weight: 500;
  color: #3c4043;
  margin-bottom: 24px;
}
.filter-group {
  margin-bottom: 28px;
}
.filter-label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #3c4043;
  margin-bottom: 12px;
}


.chip-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.chip-radio-group :deep(.el-radio-button__inner) {
  border-radius: 16px !important;
  border: 1px solid #dadce0;
  background-color: #fff;
  color: #3c4043;
  padding: 8px 16px;
  font-size: 14px;
  font-weight: 400;
  box-shadow: none !important;
  height: auto;
  display: flex;
  align-items: center;
  gap: 6px;
  line-height: 1.2;
}
.chip-radio-group :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
  border-color: transparent;
}
.chip-radio-group.sort-chips :deep(.el-radio-button__inner) {
  padding: 6px 14px;
  font-size: 13px;
}



.sort-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 24px;
}
.total-text {
  font-size: 14px;
  color: #5f6368;
}


.resource-grid-container {
  min-height: 400px;
}
.resource-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); /* 调整最小宽度 */
  gap: 24px;
}


.pagination-container {
  display: flex;
  justify-content: center;
  margin: 40px 0 16px 0;
}
</style>